package com.cskaoyan.shopping.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.shopping.dto.CartProductDto;
import com.cskaoyan.shopping.form.CartRequest;
import com.cskaoyan.shopping.form.CheckAllItemRequest;
import com.cskaoyan.shopping.service.ICartService;
import com.netflix.client.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author : bunnyupup
 * @description :
 * @date : Created in 2022/8/24 23:15
 */
@RestController
@RequestMapping("/shopping")
public class CbjShoppingController {
    @Autowired
    ICartService cartService;

    /**
     * 获得购物车列表
     * @param request
     * @return
     */
    @GetMapping("carts")
    public ResponseData GetCartList(HttpServletRequest request){
        // 获得userId
        String userInfo = request.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("uid").toString());
        List<CartProductDto> cartList = cartService.getCartListById(uid);
        ResponseData responseData = new ResponseUtil().setData(cartList);
        return responseData;
    }

    /**
     * 添加商品到购物车
     */
    @PostMapping("carts")
    public ResponseData AddCart(@RequestBody CartRequest cartRequest){
        cartService.addToCart(cartRequest);
        return new ResponseUtil().setData(null);
    }

    /**
     * 更新购物车中的商品
     */
    @PutMapping("carts")
    public ResponseData UpdateCart(@RequestBody CartRequest cartRequest){
        cartService.updateCartNum(cartRequest);
        return new ResponseUtil().setData(null);
    }

    /**
     * 删除购物车商品
     */
    @DeleteMapping("carts/{uId}/{itemId}")
    public ResponseData deleteCart(@PathVariable("uId") Long uId,@PathVariable("itemId") Long itemId ){
        cartService.deleteCartItem(uId,itemId);
        return  new ResponseUtil().setData(null);
    }


    /**
     * 全选
     */
    @PutMapping("items")
    public ResponseData checkAllCartItem(@RequestBody CheckAllItemRequest request){
        cartService.checkAllCartItem(request);
        return  new ResponseUtil().setData(null);
    }

    /**
     *删除选中
     */
    @DeleteMapping("items/{uId}")
    public ResponseData deleteCheckAllCartItem(@PathVariable("uId") Long uid ){
        cartService.deleteCheckedItem(uid);
        return  new ResponseUtil().setData(null);
    }



}
